<template>
  <div>
    <el-dialog
      :title="manageInfo.isAdd ? '新增商品' : '修改商品'"
      :visible.sync="manageInfo.isShow"
      :before-close="cancel"
      center
      @opened="createEditor"
    >
      <el-form :model="manageForm" ref="manageForm" :rules="rules">
        <!-- 一级 -->
        <el-form-item
          label="一级分类"
          :label-width="formLabelWidth"
          prop="first_cateid"
        >
          <el-select
            v-model="manageForm.first_cateid"
            placeholder="请选择一级分类"
            @change="chooseCate(true)"
          >
            <el-option
              :label="items.catename"
              v-for="items in $store.getters['cate/getCate']"
              :key="items.id"
              :value="items.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 二级 -->
        <el-form-item
          label="二级分类"
          :label-width="formLabelWidth"
          prop="second_cateid"
        >
          <el-select
            v-model="manageForm.second_cateid"
            placeholder="请选择二级分类"
          >
            <el-option
              :label="ite.catename"
              :value="ite.id"
              v-for="ite in firstAttrList"
              :key="ite.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 商品名称 -->
        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="goodsname"
        >
          <el-input
            v-model="manageForm.goodsname"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 价格 -->
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="manageForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 市场价格 -->
        <el-form-item
          label="市场价格"
          :label-width="formLabelWidth"
          prop="market_price"
        >
          <el-input
            v-model="manageForm.market_price"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 图片 -->
        <el-form-item label="图片" :label-width="formLabelWidth" prop="img">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="onChange"
            :auto-upload="false"
            :file-list="fileList"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <!-- 商品规格 -->
        <el-form-item
          label="商品规格"
          :label-width="formLabelWidth"
          prop="specsid"
        >
          <el-select
            v-model="manageForm.specsid"
            placeholder="请选择商品规格"
            @change="chooseSpecs(true)"
          >
            <el-option
              v-for="item in secondAttrList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 规格属性 -->
        <el-form-item
          label="规格属性"
          :label-width="formLabelWidth"
          prop="specsattr"
        >
          <el-select
            v-model="manageForm.specsattr"
            placeholder="请选择规格属性"
            multiple
          >
            <el-option
              :label="item.specsname"
              v-for="item in attrArr"
              :key="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 是否新品 -->
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <!-- <el-select v-model="manageForm.isnew" placeholder="请选择活动区域"> -->
          <el-radio-group v-model="manageForm.isnew">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
          <!-- </el-select> -->
        </el-form-item>
        <!-- 是否热卖 -->
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio-group v-model="manageForm.ishot">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="manageForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
        <!-- 商品描述 -->
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import {
  getSpecslist,
  goodsadd,
  goodsedit,
  goodsinfo,
} from "../../require/api";
//
import E from "wangeditor";
export default {
  data() {
    return {
      manageForm: {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", // 商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, //是否新品     1-是 2-否
        ishot: 1, //是否热卖推荐 1-是 2-否
        status: 1, //状态1正常2禁用
      },
      formLabelWidth: "120px",
      rules: {
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "change" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "change" },
        ],
        specsattr: [
          { required: true, message: "请选择商品规格属性", trigger: "blur" },
        ],
      },
      dialogImageUrl: "",
      dialogVisible: false,

      // 一级分类下的children
      firstAttrList: [],
      // 规格列表
      secondAttrList: [],
      // 规格属性
      attrArr: [],
      // 上传图片文件列表
      fileList: [],

      // 富文本编辑器
      editor: null,
    };
  },
  props: ["manageInfo"],
  methods: {
    ...mapActions({
      getManageAction: "manage/getManageAction",
      getCateAction: "cate/changeCateAction",
      getCountAction: "manage/getCountAction",
    }),

    // 封装一个创建编辑器方法
    createEditor() {
      //初始化编辑器
      this.editor = new E("#editor");
      // 创建
      this.editor.create();
      //内容的设置 editor.txt.html("要设置的内容可以是html语法");
      this.editor.txt.html(this.manageForm.description);
      console.log(this.editor, "00000");
    },
    //已上传的文件时的钩子
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 文件列表移除文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    onChange(file, fileList) {
      //给img 赋值
      this.manageForm.img = file.raw;
    },
    // 一级分类选中的pid帮助选择children完成二级分类
    chooseCate(n) {
      let index = this.cateList.findIndex(
        (item) => this.manageForm.first_cateid == item.id
      );
      this.firstAttrList = this.cateList[index].children;
      //   判断是否为新增 若为新增则清空二级目录选项 若是数据回显 不能清空
      if (n) {
        this.manageForm.second_cateid = "";
      }
      //   console.log(this.firstAttrList);
    },

    //封装获取商品规格的接口
    getSpecs() {
      getSpecslist().then((res) => {
        // console.log(res);
        this.secondAttrList = res.list;
        console.log(this.secondAttrList, "this.secondAttrList");
      });
    },

    // 商品规格选中下的属性
    chooseSpecs(n) {
      let index = this.secondAttrList.findIndex(
        (item) => this.manageForm.specsid == item.id
      );
      this.attrArr = this.secondAttrList[index].attrs;
      if (n) {
        this.manageForm.specsattr = [];
      }
    },
    // on-exceed	文件超出个数限制时的钩子	function(files, fileList)
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 清空提示
    reset() {
      this.manageForm = {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", // 商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, //是否新品     1-是 2-否
        ishot: 1, //是否热卖推荐 1-是 2-否
        status: 1, //状态1正常2禁用
      };
      //   验证清空
      this.$refs.manageForm.resetFields();
      //清空上传图片文件
      this.fileList = [];
      //销毁实例
      this.editor.destroy();
    },
    // 取消
    cancel() {
      this.reset();
      this.$emit("cancel", false);
    },

    //数据回显
    lookup(id) {
      //   console.log(id);
      //请求一条数据
      goodsinfo({ id }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.manageForm = res.list;
          // 图片回显
          this.fileList = this.manageForm.img
            ? [{ url: this.manageForm.img }]
            : [];
          this.manageForm.id = id;
          //规格属性回显时转成数组
          this.manageForm.specsattr = this.manageForm.specsattr.split(",");

          // 给富文本编辑器设置内容
          this.editor.txt.html(this.manageForm.description);

          //   回显不清空二级内容
          this.chooseCate(false);
          this.chooseSpecs(false);
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 确认
    confirm() {
      this.$refs.manageForm.validate((valid) => {
        console.log(this.manageForm);
        //取值
        this.manageForm.description = this.editor.txt.html();
        if (valid) {
          // 规格属性转成字符串
          this.manageForm.specsattr = this.manageForm.specsattr.join(",");
          // 新增
          if (this.manageInfo.isAdd) {
            // 请求接口
            goodsadd(this.manageForm).then((res) => {
              if (res.code == 200) {
                // 成功提示
                this.$message.success(res.msg);
                // 关闭弹窗 清除内容
                this.cancel();
                // 更新页面
                this.getSpecs();
                this.getCountAction();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            // 修改
            goodsedit(this.manageForm).then((res) => {
              if (res.code == 200) {
                this.cancel();
                // 更新页面
                this.getSpecs();
                this.getCountAction();
                this.getManageAction();
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          this.$message.error("验证失败了");
          return false;
        }
      });
    },
  },
  computed: {
    ...mapGetters({
      goodsList: "manage/getGoods",
      cateList: "cate/getCate",
    }),
  },
  mounted() {
    if (this.$store.getters["cate/getCate"].length == 0) {
      this.$store.dispatch("cate/getCateAction");
    }

    if (this.$store.getters["specs/getSpecs"].length == 0) {
      this.$store.dispatch("specs/getSpecsAction");
    }

    this.getManageAction();
    this.getSpecs();
    this.getCountAction();
    // // 实例化wangeditor
    // this.editor = new E("#editor");
  },
};
</script>
<style lang=less scoped >
</style>
